  
#include <cegfx/cexmlhelper.h>
#include <libxml/tree.h>
#include <string.h>

ceXmlHelper::ceXmlHelper ()
{
}

bool ceXmlHelper::HasAttribute (xmlNode* node, const char* attributeName)
{
  if (!node)
    {
      return false;
    }

  for (xmlAttr* attr = node->properties; attr; attr = attr->next)
    {
      if (strcmp ((const char*)attr->name, attributeName) == 0)
        {
          return true;
        }
    }
  return false;
}

const char* ceXmlHelper::GetAttribute (xmlNode* node, const char* attributeName, const char* defaultValue)
{
  if (!node)
    {
      return "";
    }

  for (xmlAttr* attr = node->properties; attr; attr = attr->next)
    {
      if (strcmp ((const char*)attr->name, attributeName) == 0)
        {
          return (const char*)attr->children->content;
        }
    }
  return defaultValue;
}

unsigned ceXmlHelper::GetNumberOfChildren(xmlNode *node, const char* tagName)
{
  unsigned num=0;
  if (!node)
    {
      return num;
    }

  bool testTagName = strlen(tagName) != 0;

  for (xmlNode* child = node->children; child; child = child->next)
    {
      if (child->type == XML_ELEMENT_NODE && 
          (!testTagName  ||
          strcmp ((const char*)child->name, tagName) == 0))
        {
          num++;
        }
    }

  return num;
}

xmlNode* ceXmlHelper::GetChild(xmlNode* parent, const char* tagName)
{
  return ceXmlHelper::GetChild (parent, 0, tagName);
}

xmlNode* ceXmlHelper::GetChild(xmlNode *parent, unsigned int idx, const char* tagName)
{
  if (!parent)
    {
      return 0;
    }

  unsigned num=0;
  bool testTagName = strlen(tagName) != 0;

  for (xmlNode* child = parent->children; child; child = child->next)
    {
      if (child->type == XML_ELEMENT_NODE && 
          (!testTagName  ||
          strcmp((const char*)child->name, tagName) == 0))
        {
          if (num == idx)
            {
              return child;
            }
          num++;
        }
    }
  return 0;
}

